package membership_v1

import (
	"context"
	"errors"
	"gf-xb-api/internal/consts"
	"gf-xb-api/internal/dao"
	"gf-xb-api/internal/model/dto"
	"gf-xb-api/internal/model/entity"

	"golang.org/x/crypto/bcrypt"
)

func (s *sMembership) Login(ctx context.Context, in *dto.LoginInput) (*entity.SysUser, error) {
	defaultErr := errors.New(consts.JWT_ERRFAILEDAUTHENTICATION)

	// 验证账号密码是否正确
	var user *entity.SysUser
	if err := dao.SysUser.Ctx(ctx).Where(dao.SysUser.Columns().Username, in.Username).Scan(&user); err != nil {
		return nil, defaultErr
	}

	if user == nil {
		return nil, defaultErr
	}

	if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(in.Password)); err != nil {
		return nil, defaultErr
	}

	if user.Status == uint(consts.USER_STATUS_INACTIVE) {
		return nil, errors.New(consts.JWT_ErrLoginInactiveMsg)
	}

	return user, nil
}
